<?php

require_once 'Zend/View.php';
require_once 'Zend/Controller/Front.php';

class Core_Widget_Validate extends Core_Widget_Abstract
{
	protected $data;
	protected $message;
	protected $transform;
	
	public function validate($all = true)
	{
		$rules = $this->rules();
		$validrules = ($all===true)?array_keys($rules):explode(',', $all);

		foreach($validrules as $rule)
		if(!empty($rules[$rule]['valid']))
		{
			$validators = new Zend_Validate();
			foreach($rules[$rule]['valid'] as $validator)
				$validators->addValidator($validator);
			
			if(!$validators->isValid($this->getData($this->getTransform($rule))))
				$this->setMessage($this->getTransform($rule), array_values($validators->getMessages()));

		}
		return !$this->hasMessage();
	}
	
	public function rules()
	{
		return array();
	}
	
	public function clear()
	{
		$this->clearData();
		$this->clearTransform();
		$this->clearMessage();
		return $this;
	}
	
  public function getTransform($index = null)
  {
		if($index === null)
			return $this->transform;
		
    return empty($this->transform[$index])?$index:$this->transform[$index];
  }
  
  public function setTransform($transform)
  {
		$this->transform = $transform;
		return $this;
  }
  
  public function clearTransform()
  {
		unset($this->transform);
  	return $this;
  }

  public function getData($index = null)
  {
		if($index === null)
			return $this->data;
		
    return @$this->data->{$index};
  }

  public function filter($index)
  {
		$rules 	= $this->rules();
		$data 	= $this->data->{$index};
		
		if(!empty($rules[$index]['filter']))
		{
			foreach($rules[$index]['filter'] as $filter)
			{
				$data = $filter->filter($data);
			}
		}

    return $data;
  }
  
  public function setData($data)
  {
		$this->data = is_array($data)?((object) $data):$data;
		return $this;
  }
  
  public function clearData()
  {
		unset($this->data);
  	return $this;
  }
  
  public function hasMessage($index = null)
  {
    $messages = $this->message;

    if($index === null)
    {
      return empty($messages)?false:true;
    }
    return empty($messages[$index])?false:true;
  }

  public function getMessage($index = null)
  {
    return ($index === null)?$this->message:@$this->message[$index];
  }
  
  public function setMessage($key, $val = null)
  {
    $stores   = $this->message;
    $messages = is_array($key)?$key:array($key=>$val);
    
    foreach($messages as $k=>$v)
      $stores[$k] = $v;
    
    $this->message = $stores;
    return $this;
  }
  
  public function clearMessage()
  {
   $this->message = array(); 
   return $this;
  }
}